package mvc.view.components {
	import flash.display.Sprite;
	import flash.utils.Dictionary;

	public class StageSprite {
		private var _container:Sprite;
		private var _layers:Array = [];
		private var _layerNameMap:Dictionary = new Dictionary();

		public function StageSprite(stage:Sprite) {
			_container = stage;
		}

		public function addLayer(sprite:Sprite, name:String, z:int):Sprite {
			if (_layerNameMap[name])
				throw new Error("The name: " + name + " has already been added.");

			var layer:Object = new Object();
			layer.name = name;
			layer.sprite = sprite;
			layer.z = z;

			var i:int = getInsertPosition(_layers, z);
			_layers.splice(i, 0, layer);
			_layerNameMap[name] = layer;
			_container.addChildAt(layer.sprite, i);
			return layer.sprite;
		}

		public function removeLayerByName(name:String):void {
			var len = _layers.length;
			for (var i:int = 0; i < len; i++) {
				var item:Object = _layers[i];
				if (item.name == name) {
					_container.removeChildAt(i);
					_layers.splice(i, 1);
					delete _layerNameMap[name];
					return;
				}
			}
		}

		public function removeLayerById(z:int):void {
			var len = _layers.length;
			for (var i:int = 0; i < len; i++) {
				var item:Object = _layers[i];
				if (item.z == z) {
					_container.removeChildAt(i);
					_layers.splice(i, 1);
					delete _layerNameMap[item.name];
				}
			}
		}

		public function getLayer(name:String):Sprite {
			return _layerNameMap[name];
		}

		private function getInsertPosition(arr:Array, z:int):int {
			var len:int = arr.length;
			if (len == 0)
				return 0;

			for (var i:int = 0; i < len; i++) {
				if (z < arr[i].z)
					return i;
			}
			return len;
		}
	}
}
